package p.ithorns.tools.translator.sdk.handler;

import com.google.auto.service.AutoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import p.ithorns.tools.translator.annotation.field.BeanField;
import p.ithorns.tools.translator.annotation.Translator;
import p.ithorns.tools.translator.sdk.provider.DictStandardProvider;
import p.ithorns.tools.translator.sdk.exception.DictFieldException;

import java.io.Serializable;
import java.util.Map;
import java.util.Set;

/**
 * BeanTranslator
 *
 * Bean转换
 * 需要字典提供者实现DictStandardProvider接口
 *
 * @author Ht.L
 * @date 2025-02-05 22:28
 * @since 1.0.0
 */
@AutoService(Translator.class)
public class BeanTranslator implements Translator<Serializable, BeanField> {

    // private static final Logger log = LoggerFactory.getLogger(BeanTranslator.class);

    private final ApplicationContext appCtx;


    public BeanTranslator(ApplicationContext appCtx) {
        this.appCtx = appCtx;
    }

    @Override
    @SuppressWarnings("unchecked")
    public String translate(BeanField annotation, Serializable key) {
        String beanName = annotation.bean();
        try {
            DictStandardProvider<Serializable, Object> bean = appCtx.getBean(beanName, DictStandardProvider.class);
            return (String) bean.getDict(key);
        } catch (NoSuchBeanDefinitionException e) {
            String msg = String.format("@BeanField: No such bean: [%s]", beanName);
            throw new DictFieldException(msg, e);
        } catch (Exception e) {
            String msg = String.format("@BeanField: Failed to invoke #getDict on bean: [%s]", beanName);
            throw new DictFieldException(msg, e);
        }
    }

    @Override
    @SuppressWarnings({"unchecked"})
    public Map<Serializable, Object> translate(BeanField annotation, Set<Serializable> keys) {
        String beanName = annotation.bean();
        try {
            DictStandardProvider<Serializable, Object> bean = appCtx.getBean(beanName, DictStandardProvider.class);
            return bean.getDictMap(keys);
        } catch (NoSuchBeanDefinitionException e) {
            String msg = String.format("@BeanField: No such bean: [%s]", beanName);
            throw new DictFieldException(msg, e);
        } catch (Exception e) {
            String msg = String.format("@BeanField: Failed to invoke #getDict on bean: [%s]",beanName);
            throw new DictFieldException(msg, e);
        }
    }

}